package com.ayh.campusfun.controller.api.v1;

import com.ayh.campusfun.common.CommonResult;
import com.ayh.campusfun.common.core.jwt.JWTUtils;
import com.ayh.campusfun.common.exception.http.ForbiddenException;
import com.ayh.campusfun.entity.TopicComment;
import com.ayh.campusfun.entity.Users;
import com.ayh.campusfun.service.TopicCommentService;
import com.ayh.campusfun.service.TopicShareService;
import com.ayh.campusfun.vo.AddCommentVO;
import com.ayh.campusfun.vo.CommentVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 话题评论表(TopicComment)表控制层
 *
 * @author ayh
 * @since 2021-03-20 20:42:41
 */
@RestController
@RequestMapping("topicComment")
public class TopicCommentController {
    /**
     * 服务对象
     */
    @Autowired
    private TopicCommentService topicCommentService;

    @Autowired
    private  TopicShareService topicShareService;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Resource
    private JWTUtils jwtUtils;

    @PostMapping(value = "/findCommentList",produces = "application/json")
    public CommonResult getCommentList(Long topicId){
        Map<String,Object> map = new HashMap<>();
        map.put("topicId",topicId);
        List<CommentVO<TopicComment>> commentVOS = CommentVO.buildTopicCommentList(topicCommentService.findListByParam(map));
        return CommonResult.success(commentVOS);
    }

    @PostMapping(value = "/addComment",produces = "application/json")
    public CommonResult addComment(HttpServletRequest request, TopicComment comment){
        String authorization = jwtUtils.getTokenFromRequest(request);
        Users users = (Users) redisTemplate.opsForValue().get(authorization);
        if(users==null){
            throw new ForbiddenException(60009);
        }
        comment.setUid(users.getUid());
        comment.setAvatarUrl(users.getAvatarUrl());
        comment.setNickName(users.getNickName());
        topicCommentService.insert(comment);
        topicShareService.commentById(comment.getTopicId());
        TopicComment byId = topicCommentService.findById(comment.getId());
        AddCommentVO<TopicComment> addCommentVO = new AddCommentVO<>();
        BeanUtils.copyProperties(byId,addCommentVO);
        addCommentVO.setChildList(new ArrayList<>());
        return CommonResult.success(addCommentVO);
    }

}
